package com.seeyon.apps.cxgd.service.tc;

import com.seeyon.apps.cxgd.entity.ResountEntity;
import com.seeyon.apps.cxgd.kit.FormCap4Kit;
import com.seeyon.apps.cxgd.kit.LogKit;
import com.seeyon.apps.cxgd.kit.StrKit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 回推机票的service
 */
public class JPOrderService {
    private static Log log = LogFactory.getLog(JPOrderService.class);
    private CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");
    private CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager)AppContext.getBean("cap4FormDataManager");
    private OrgManager orgManager = (OrgManager)AppContext.getBean("orgManager");
    private final static String JP_NUMBER = "TCHDDXX_001";


    /**
     * 回写机票表单数据
     * @param notifyData     推送主体
     * @param subNotifyType  推送子类型
     * @return
     */
    public ResountEntity JpOrder(String notifyData, String subNotifyType) throws Exception {
        log.info("推送机票订单数据："+notifyData);

        Map<String,Object> dataMap = null;
        //获取订单详情
        Map<String,Object> orderDetailsMap = null;
        //获取差旅信息
        Map<String,Object> travelData = null;
        //获取订单号
        String orderSerialNo = "";
        //oa申请单号
        String travelApplyNo = "";
        try{
            JSONObject jsonObject = JSON.parseObject(notifyData);
            dataMap = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("data")),Map.class);
            orderDetailsMap = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("orderDetails")),Map.class);
            travelData = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("travelData")),Map.class);
            orderSerialNo = StrKit.str(orderDetailsMap.get("orderSerialNo"));
            travelApplyNo = StrKit.str(travelData.get("travelApplyNo"));
        }catch (Exception e){
            log.info("解析同城回退订单-火车数据异常！",e);
        }




        LogKit.addLog("同程回退订单-机票【订单号："+orderSerialNo+"；OA申请单号："+travelApplyNo+"】", "同程回退订单-机票【订单号："+orderSerialNo+"；OA申请单号："+travelApplyNo+"】", notifyData, "subNotifyType状态："+subNotifyType);
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //获取原定单号
        String originalOrderNo = StrKit.str(orderDetailsMap.get("originalOrderNo"));
        //获取人员组Id
        String outEmployeeIdZ = StrKit.str(orderDetailsMap.get("outEmployeeId"));
        //订单状态
        String orderStatusText = StrKit.str(orderDetailsMap.get("orderStatusText"));
        //获取航段信息
        List<Map<String,Object>> segmentList = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("flightSegmentList")),List.class);
        //获取机票出发时间
        String departTime = StrKit.str(segmentList.get(0).get("departTimeFull"));
        LocalDateTime dateTime = LocalDateTime.parse(departTime, inputFormatter);
        departTime = dateTime.format(outputFormatter);
        //获取机票出发地
        String departAirport = StrKit.str(segmentList.get(0).get("departAirport"))+StrKit.str(segmentList.get(0).get("departTerminal"));
        //获取到达时间
        String arriveTime = StrKit.str(segmentList.get(segmentList.size()-1).get("arriveTimeFull"));
        LocalDateTime arriveDateTime = LocalDateTime.parse(arriveTime, inputFormatter);
        arriveTime = arriveDateTime.format(outputFormatter);
        //获取机票目的地
        String arriveAirport = StrKit.str(segmentList.get(segmentList.size()-1).get("arriveAirport"))+StrKit.str(segmentList.get(segmentList.size()-1).get("arriveTerminal"));
        //获取人员信息
        List<Map<String,Object>> passengerList = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("passengerList")),List.class);

        //保存表单数据集合
        List<HashMap<String,Object>> maps = new ArrayList<>();
        for (Map<String, Object> map : passengerList) {
            //外部员工id
            String outEmployeeId = StrKit.str(map.get("outEmployeeId"));
            //票价
            String price = StrKit.str(map.get("salesPrice"));
            V3xOrgMember member = null;
            try {
                member = orgManager.getMemberById(Long.valueOf(outEmployeeId));
            } catch (BusinessException e) {
                log.info("机票订单-根据外部人员获取人员Id 异常！", e);
            }

            //获取需要回写的字段信息
            HashMap<String, Object> hcMap = new HashMap<>();
            hcMap.put("出差人工号",member != null?member.getCode():"");
            hcMap.put("出差人",member != null?member.getId():"");
            hcMap.put("出差申请单号",travelApplyNo);
            hcMap.put("订单类型","机票订单");
            hcMap.put("订单状态",orderStatusText);
            if(orderStatusText.equals("退票成功")){
                if(!price.contains("-")){
                    price = "-"+price;
                }
            }
            hcMap.put("价格",price);

            hcMap.put("出发入住日期",departTime);
            hcMap.put("到达离开日期",arriveTime);
            hcMap.put("出发地",departAirport);
            hcMap.put("目的地",arriveAirport);
            hcMap.put("同程单号",orderSerialNo);
            hcMap.put("上车地点","");
            hcMap.put("下车地点","");
            hcMap.put("原订单号",originalOrderNo);

            //组装主表和明细表数据map
            HashMap<String,Object> mapData = new HashMap<>();
            mapData.put("masterData",hcMap);
            mapData.put("mxData",null);
            maps.add(mapData);
        }
        try {
            if(!outEmployeeIdZ.equals("")){
                V3xOrgMember orgMember = orgManager.getMemberById(Long.valueOf(outEmployeeIdZ));
                if(orgMember == null){
                    log.info("获取人员【"+outEmployeeIdZ+"】异常！");
                    return new ResountEntity(true,"1","回写机票订单失败");
                }
                FormCap4Kit.saveCAP4FormData(orgMember,JP_NUMBER,maps,false);
            }else{
                log.info("获取组负责人【"+outEmployeeIdZ+"】为空！");
            }
        } catch (Exception e) {
            log.info("添加机票数据失败：",e);
        }
        return new ResountEntity(true,"100","回写机票订单成功");
    }



    //订单类型转换
    private String getOrderType(int type){
        String typeString = "";
        switch (type){
            case 0:
                typeString = "国际";
                break;
            case 1:
                typeString = "国内";
                break;
        }
        return typeString;
    }


    //订单状态转换
    private String getOrderStatus(int status){
        String statusString = "";
        switch (status){
            case 0:
                statusString = "待审批";
                break;
            case 3:
                statusString = "待提交";
                break;
            case 4:
                statusString = "占座中";
                break;
            case 22:
                statusString = "出票失败";
                break;
            case 40:
                statusString = "退票待审批";
                break;
            case 41:
                statusString = "退票待确认";
                break;
            case 42:
                statusString = "退票中";
                break;
            case 47:
                statusString = "退票失败";
                break;
            case 48:
                statusString = "退票审批不通过";
                break;
            case 49:
                statusString = "取消退票";
                break;
            case 60:
                statusString = "改签待审批";
                break;
            case 63:
                statusString = "改签成功";
                break;
            case 64:
                statusString = "部分改签";
                break;
            case 66:
                statusString = "取消改签";
                break;
            case 67:
                statusString = "改签失败";
                break;
            case 68:
                statusString = "改签审批不通过";
                break;
            case 92:
                statusString = "待确认";
                break;
            case 93:
                statusString = "改签中";
                break;
            case 94:
                statusString = "部分退票";
                break;
            case 95:
                statusString = "退票成功";
                break;
            case 96:
                statusString = "已取消";
                break;
            case 97:
                statusString = "已出票";
                break;
            case 98:
                statusString = "出票中";
                break;
            case 99:
                statusString = "待付款";
                break;

        }
        return statusString;
    }


    /**
     * 切换订单子类型
     * 1-占座 2-出票 3-退票 4-邮寄 5-占座出票合并 6-订单过期 7-支付 8-购保 9-退保 10-抢票出票 11-抢票过期 12-抢票占座 13-取消订单 14-停运 15-H5出票推送
     * @return
     */
    private String getSubNotifyType(String subNotifyType){
        if(subNotifyType.equals("1")){
            subNotifyType = "占座";
        }else if(subNotifyType.equals("2")){
            subNotifyType = "出票";
        }else if(subNotifyType.equals("3")){
            subNotifyType = "退票";
        }else if(subNotifyType.equals("4")){
            subNotifyType = "改签完成";
        }else if(subNotifyType.equals("5")){
            subNotifyType = "改签失败";
        }else if(subNotifyType.equals("6")){
            subNotifyType = "订单取消";
        }else if(subNotifyType.equals("7")){
            subNotifyType = "退票失败";
        }else if(subNotifyType.equals("8")){
            subNotifyType = "占座失败";
        }else if(subNotifyType.equals("9")){
            subNotifyType = "改签确认成功";
        }else if(subNotifyType.equals("11")){
            subNotifyType = "改签确认失败";
        }else if(subNotifyType.equals("12")){
            subNotifyType = "退票确认成功";
        }else if(subNotifyType.equals("13")){
            subNotifyType = "退票确认失败";
        }else if(subNotifyType.equals("14")){
            subNotifyType = "Q消息推送";
        }
        return subNotifyType;
    }

    /**
     * 给主表
     * @param masterId
     * @param formBean
     * @param filedName
     * @param fieldValue
     * @throws BusinessException
     * @throws SQLException
     */
    private void updateWuxiao(Long masterId,FormBean formBean,String filedName,String fieldValue) throws BusinessException, SQLException {
        FormDataMasterBean dataMasterBean = cap4FormManager.findDataById(masterId, formBean, null);
        dataMasterBean.addFieldValue(filedName,fieldValue);
        cap4FormDataManager.insertOrUpdateMasterData(dataMasterBean);
    }



}
